package com.pulse.common.utils.sor.make;

import com.pulse.common.utils.sor.domain.SorInfo;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName DataPtsMake
 * @Description
 * @Author 陆帅
 * @Date 2025/3/14 23:00
 */
public class DataPtsMake {

    public static final String DATA_POINTS_BLOCK_ID = "DataPts\0";

    public static ByteBuffer make(SorInfo info) {

        int byteCount = info.getDataPts().getTracedata().size() * 2 + 20;

        ByteBuffer buffer = ByteBuffer.allocate(byteCount);
        buffer.order(ByteOrder.LITTLE_ENDIAN);

        // 块ID
        buffer.put(DATA_POINTS_BLOCK_ID.getBytes());
        // 写入数据点数量
        long numDataPoints = info.getDataPts().getNumDataPoints();
        buffer.putInt((int)numDataPoints);
        // 跟踪数量
        long numTraces = info.getDataPts().getNumTraces();
        buffer.putShort((short) numTraces);
        // 根据仪表量程除以点间距得到写入数据点数
        long numDataPoints2 = info.getDataPts().getNumDataPoints2();
        buffer.putInt((int)numDataPoints2);
        // 缩放银子
        Double scalingFactor = info.getDataPts().getScalingFactor() * 1000;
        buffer.putShort((short) Math.round(scalingFactor));

        List<Double> datas = new ArrayList<>();
        Double min = Double.MAX_VALUE;
        Double max = Double.MIN_VALUE;
        for (String tracedatum : info.getDataPts().getTracedata()) {
            Double value = Double.parseDouble(tracedatum.split("\t")[1]) * 1000;
//            buffer.putShort(value.shortValue());
            datas.add(value);
            if(value > max){
                max = value;
            }
            if(value < min)
            {
                min = value;
            }
        }

        for (Double data : datas) {
            Double v = max - data;
            buffer.putShort((short) Math.round(v));
        }

        return buffer;
    }
}
